//
//  LYPictuerController.swift
//  微博
//
//  Created by liuerying on 16/5/29.
//  Copyright © 2016年 liuerying. All rights reserved.
//

import UIKit
import SnapKit
private let PictureCellID = "PictureCellID"
//每行几个
private let colCount:CGFloat = 4
//间距u
private let magin:CGFloat = 3

//最大张数
private let maxImageCount = 4
//宽
private let itemWidth = (ScreeWidth - (colCount+1)*magin) / colCount

class LYPictuerController: UICollectionViewController {

    //定义图片数组
    lazy var images : [UIImage] = [UIImage]()
    
    init(){
    
        let flayLayout = UICollectionViewFlowLayout()
        flayLayout.itemSize = CGSizeMake(itemWidth, itemWidth)
        flayLayout.minimumLineSpacing = magin
        flayLayout.minimumInteritemSpacing = magin
        
        flayLayout.sectionInset = UIEdgeInsetsMake(magin, magin, 0, magin)
        super.init(collectionViewLayout: flayLayout)
        
        //注册cell
        self.collectionView?.registerClass(LYPictueritemCell.self, forCellWithReuseIdentifier: PictureCellID)
        
        //设置背景颜色
         self.collectionView?.backgroundColor = UIColor.whiteColor()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
        
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
       
        
    }
    
    
 
    
}

//MARK: 数据源方法
extension LYPictuerController{

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let delta = images.count == maxImageCount ? 0 : 1
        return images.count + delta
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureCellID, forIndexPath: indexPath) as! LYPictueritemCell
        cell.backgroundColor = randomColor()
        
        cell.selectorDelegate = self

        if indexPath.item == images.count{
        
            //获取数组中的最后一个数据
            cell.image = nil
        }else{
        
            cell.image = images[indexPath.item]
        }
        
        return cell
    }
}

//MARK: 必选的协议方法 必须实现  添加图片
extension LYPictuerController: LYPictueritemCellDelegate{

    //遵守协议-添加图片
    func userWillAddPicture() {
        print("添加图片")
        
        if !UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum){
        
            print("没有访问权限")
            return
        }
        
        let picker = UIImagePickerController()
//可以编辑
//        picker.allowsEditing = true
        picker.delegate = self
        self.presentViewController(picker, animated: true, completion: nil)
    }
    
    //遵守协议-- 删除照片
    func userWillDeletePicture(cell: LYPictueritemCell) {
        print("删除照片")
        
        //根据cell 得到indexPath
        guard let indexPath = collectionView?.indexPathForCell(cell) else{
        
            return
        }
        
        //根据indexPath删除所对应的照片
        images.removeAtIndex(indexPath.item)
        
        collectionView?.reloadData()
        
        
    }
}

//MARK: 遵守图片选择器的协议-代理
extension LYPictuerController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {

    //实现选择图片的协议方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        print(image)
        
        print("------")
        print(editingInfo)
        
        //保存图片
        
        images.append(image)
        
        self.collectionView?.reloadData()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}


//定义协议
@objc protocol LYPictueritemCellDelegate: NSObjectProtocol{

    //定义协议方法
    optional func userWillAddPicture()
    optional func  userWillDeletePicture(cell: LYPictueritemCell)
}

//MARK: 自定义的cell
class LYPictueritemCell: UICollectionViewCell{

    
    var image:UIImage?{
        didSet{
        
            //完成给按钮设置图片  隐藏添加按钮
            deleteBtn.hidden = image == nil
            addBtn.setImage(image, forState: .Normal)
        }
        
    }
    
    //代理对象的属性
    weak var selectorDelegate:LYPictueritemCellDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
  @objc  private func addBtnClick(){
    
//        print("添加站片")
        selectorDelegate?.userWillAddPicture?()
    }
    
   @objc private func deleteBtnClick(){
    
//        print("取消")
  
    selectorDelegate?.userWillDeletePicture?(self)
    }
    
    //设置UI界面
    private func setupUI(){
    
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        //设置约束
        addBtn.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        
        deleteBtn.snp_makeConstraints { (make) in
            make.top.right.equalTo(contentView)
        }
        
        
        
        //添加点击按钮事件
        addBtn.addTarget(self, action: #selector(LYPictueritemCell.addBtnClick), forControlEvents: .TouchUpInside)
        
        //添加点击dele小按钮的点击事件
        deleteBtn.addTarget(self, action: #selector(LYPictueritemCell.deleteBtnClick), forControlEvents: .TouchUpInside)
        
    }
    
    
    //懒加载控件
    private lazy var addBtn:UIButton = {
    
        let btn = UIButton()
        
        btn.setBackgroundImage(UIImage(named:"compose_pic_add"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named:"compose_pic_add_highlighted"), forState: .Highlighted)
  
        //设置图片的样式
        btn.imageView?.contentMode = .ScaleAspectFill
        
        btn.imageView?.clipsToBounds = true

        return btn
        
    }()
    
    private lazy var deleteBtn:UIButton = {
    
        let btn = UIButton()
        
        btn.setImage(UIImage(named:"compose_photo_close"), forState: .Normal)
       
        return btn
    }()
    
    
}